<?php 
class MenuComponent extends Object {
	var $components = array('Session','Auth','Acl','Pippoacl.ControllerList');
	
	//avoid some of the controller, controller that don't have a menu
	public $avoidControllers   = array('Pages', 'Utils','App');
	
	//menu displayed in every page
	public $everMenu = array('Home' => '/');
	
	//public menu items, menu stuff that don't need authentication
	public $publicMenu   = array('Register'=>'/users/register','Forget'=> '/users/forget');
	
	//action that don't need to be included in menu
	public $avoidActions   = array('switch_language','forget','reset','register','activate','adjustperm','login','logout');
	
	//user login menu
	public $userLogin = array('Login' => '/users/login');
	
	//user logout menu
	public $userLogout = array('Logout' => '/users/logout');
	
	function startup() {
		
		if (!$this->Auth->user()) {
			//build public menu
			$menu=$this->createpublicMenu();
			$this->Session->write('pippomenu', $menu);
		}else{
			//build user menu
			$menu=$this->createuserMenu($this->Auth->user());
			$this->Session->write('pippomenu', $menu);
		}
 
	}

	function createpublicMenu () {
		$mymenu=$this->everMenu;
		$mymenu=array_merge($mymenu,$this->publicMenu);
		$mymenu=array_merge($mymenu,$this->userLogin);
		return $mymenu;
	}
	
	function createuserMenu ($us) {
		$mymenu=$this->everMenu;
		//App::Import('Model','Role');
		$this->Role = & ClassRegistry::init('Role'); 
        $data               = $this->Role->findAll();
        $controllerList     = $this->ControllerList->get();  
		

        // we loop on all action for all roles      
		$userroleid=$us['User']['role_id'];
		
        foreach($controllerList as $controller => $actions )                
        {
            if(in_array($controller, $this->avoidControllers))
            {
                unset($controllerList[$controller]);
                continue;
            }
            foreach($actions as $key => $action)
           	{
                $controllerList[$controller][$action] = array();          
                unset($controllerList[$controller][$key]);
                foreach($data as $p)
                {
					if ($p['Role']['id'] == $userroleid){
						if (!in_array($action,$this->avoidActions)){
							if ($this->Acl->check($p, $controller . '/'. $action, '*')) {
								$mymenuacl[$controller][$action] = "/".strtolower($controller)."/".$action;
							}
						}
					}
                }     
            }   
        }
		
		
		$mymenu=array_merge($mymenu,$mymenuacl);
		$mymenu=array_merge($mymenu,$this->userLogout);
		
		
		return $mymenu;

	}
	
}
?>